package com.wzs.rpc.proxy;

import cn.hutool.http.HttpResponse;
import com.wzs.rpc.model.RpcRequest;
import com.wzs.rpc.model.RpcResponse;
import com.wzs.rpc.serializer.JDKSerializer;
import com.wzs.rpc.serializer.Serializer;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import cn.hutool.http.HttpRequest;

public class ServiceProxy implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("调用代理类");
        Serializer serializer = new JDKSerializer();
        //构造请求
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameterTypes(method.getParameterTypes())
                .args(args)
                .build();
        //发送请求
        try {
            byte[] requestBytes = serializer.serialize(rpcRequest);
            // todo 注意，这里地址被硬编码了（需要使用注册中心和服务发现机制解决）
            try(HttpResponse response = HttpRequest.post("http://localhost:8080")
                    .body(requestBytes)
                    .execute()) {
                byte[] responseBytes = response.bodyBytes();
                RpcResponse rpcResponse = serializer.deserialize(responseBytes, RpcResponse.class);
                return rpcResponse.getData();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
